//
//  JSUIWebViewViewController.m
//  webviewshell
//
//  Created by mac on 2017/8/26.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "JSUIWebViewViewController.h"

@interface JSUIWebViewViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *JSWebView;
@end

@implementation JSUIWebViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self loadHtml];
    
//    UIWebView Delegate 委托代理
    _JSWebView.delegate = self;
    _JSWebView.dataDetectorTypes = UIDataDetectorTypeLink;
//    取消右侧，下侧滚动条，去处上下滚动边界的黑色背景
    _JSWebView.backgroundColor=[UIColor clearColor];
    for (UIView *_aView in [_JSWebView subviews])
    {
        if ([_aView isKindOfClass:[UIScrollView class]])
        {
            [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
            //右侧的滚动条
            
            [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO];
            //下侧的滚动条
            
            for (UIView *_inScrollview in _aView.subviews)
            {
                if ([_inScrollview isKindOfClass:[UIImageView class]])
                {
                    _inScrollview.hidden = YES;  //上下滚动出边界时的黑色的图片
                }
            }
        }
    }
    [self.view addSubview:_JSWebView];
}


- (void)loadHtml{
    //    第一步：创建UIWebView
    //    UIWebView *webView;
    //    webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 22, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-22)];
    
    
    //    第一种
    //    加载本地的html
    //    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
    //    NSString *path = [[NSBundle mainBundle] pathForResource:@"需要填写的webview首页" ofType:@"html"];
    //    NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //    [webView loadHTMLString:html baseURL:baseURL];
    
    
    //    第二种
    //    加载在线资源http内容
    //    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];  //创建URL
    //    NSURLRequest *request = [NSURLRequest requestWithURL:url];    //创建NSURLRequest
    //    [webView loadRequest:request];    //加载网页
    
    
    //    第三种
    //    加载本地的html
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"JSUIWebView" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:filePath];  //创建URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url];  //创建NSURLRequest
    
    [self.JSWebView loadRequest:request];
    
    //  UIWebView类内部会管理浏览器的导航动作，通过 goForward 和 goBack 方法你可以控制前进与后退动作
    [self.JSWebView goForward];
    [self.JSWebView goBack];
}

/*****************************************************************/

- (void)showMsg:(NSString *)msg {
    //初始化提示框；
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:  UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //点击按钮的响应事件；
    }]];
    
    //弹出提示框；
    [self presentViewController:alert animated:true completion:nil];
}

/*****************************************************************/

#pragma mark - JS调用OC方法列表
- (void)noParameter {
    [self showMsg:@"此次进行无参调用"];
}

- (void)strParameter:(NSString *)msg {
    NSLog(@"%@",msg);
    NSString *info = [NSString stringWithFormat:@"此次调用参数(字符串)为: %@ ",msg];
    [self showMsg:info];
}

- (void)numStrParameter:(NSString *)num msg:(NSString *)msg {
    NSString *info = [NSString stringWithFormat:@"此次调用参数(数字,字符串)为: %@, %@ ",num,msg];
    [self showMsg:info];
}

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"%@",NSStringFromSelector(_cmd));
    
    //JS调用OC是基于协议拦截实现的 下面是相关操作
    NSString *absolutePath = request.URL.absoluteString;
    
    NSString *scheme = @"yuncentry://";
    
    if ([absolutePath hasPrefix:scheme]) {
        NSString *subPath = [absolutePath substringFromIndex:scheme.length];
        
        if ([subPath containsString:@"?"]) {//1个或多个参数
            
            if ([subPath containsString:@"&"]) {//多个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                NSArray *params = [parameter componentsSeparatedByString:@"&"];
                
                if (params.count == 2) {
                    if ([self respondsToSelector:sel]) {
                        [self performSelector:sel withObject:[params firstObject] withObject:[params lastObject]];
                    }
                }
                
                
            } else {//1个参数
                NSArray *components = [subPath componentsSeparatedByString:@"?"];
                
                NSString *methodName = [components firstObject];
                methodName = [methodName stringByReplacingOccurrencesOfString:@"_" withString:@":"];
                SEL sel = NSSelectorFromString(methodName);
                
                NSString *parameter = [components lastObject];
                
                if ([self respondsToSelector:sel]) {
                    [self performSelector:sel withObject:parameter];
                }
                
            }
            
        } else {//没有参数
            NSString *methodName = [subPath stringByReplacingOccurrencesOfString:@"_" withString:@":"];
            SEL sel = NSSelectorFromString(methodName);
            
            if ([self respondsToSelector:sel]) {
                [self performSelector:sel];
            }
        }
    }
    
    return YES;
}


//开始加载网页调用此方法
- (void)webViewDidStartLoad:(UIWebView *)JSWebView
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

//网页加载完成调用此方法
- (void)webViewDidFinishLoad:(UIWebView *)JSWebView
{
    NSLog(@"%@", NSStringFromSelector(_cmd));
}

//网页加载失败调用此方法
- (void)JSWebView:(UIWebView *)JSWebView didFailLoadWithError:(NSError *)error
{
    NSLog(@"%@:%@", NSStringFromSelector(_cmd), error.localizedDescription);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
